#!/bin/bash

if (($# < 2)); then
    ./util/error.sh "merge db" "args invalid"
    exit 1
fi

#源服务器id,将合并此服务器到目标服务器
src_sid=$1
#目标服务器id
dst_sid=$2

title="$0 s$src_sid to s$dst_sid"


#
# 检测源服务器的配置
#
src_db_name=`./config/game_db_name.sh $src_sid`
if [ -z $src_db_name ]; then
    ./util/error.sh "$title" "src db name invalid"
    exit 1
fi

src_db_address=`./config/game_db_address.sh $src_sid`
if [ -z $src_db_address ]; then
    ./util/error.sh "$title" "src db address invalid"
    exit 1
fi


#
# 检查目标服务器的配置
#
dst_db_name=`./config/game_db_name.sh $dst_sid`
if [ -z $dst_db_name ]; then
    ./util/error.sh "$title" "dst db name invalid"
    exit 1
fi

dst_db_address=`./config/game_db_address.sh $dst_sid`
if [ -z $dst_db_address ]; then
    ./util/error.sh "$title" "dst db address invalid"
    exit 1
fi


#
# 清理源数据库并合并不会冲突的数据到目标数据库
#
./util/info.sh "$title" "dump/restore db ..."
rm -rf ./dump/$src_db_name
mongodump --host $src_db_address -d $src_db_name -c pay >./merge/mongo.log 2>&1
mongodump --host $src_db_address -d $src_db_name -c cash >./merge/mongodump.log 2>&1
mongodump --host $src_db_address -d $src_db_name -c analysis >./merge/mongodump.log 2>&1
mongodump --host $src_db_address -d $src_db_name -c log >./merge/mongodump.log 2>&1
mongodump --host $src_db_address -d $src_db_name -c user -q '{"status.level":{"$gt":5}}' >./merge/mongo.log 2>&1

if ((src_sid != dst_sid)); then
    mongorestore --host $dst_db_address -d $dst_db_name --directoryperdb "dump/$src_db_name" >./merge/mongo.log 2>&1
else 
    mongodump --host $src_db_address -d $src_db_name -c plat >./merge/mongo.log 2>&1
fi

mongodump --host $src_db_address -d $src_db_name -c world -q '{_id:{"$in":["league", "league_duplicate", "world_boss"]}}' >./merge/mongo.log 2>&1
mongorestore --drop --host $src_db_address -d $src_db_name --directoryperdb "dump/$src_db_name" >./merge/mongo.log 2>&1


if ((src_sid == dst_sid)); then
    ./util/info.sh "$title" "cur is dst"
    exit 0;
fi


#
# 合并冲突数据
#
./util/info.sh "$title" "merge conflict data ..."
node ./merge/merge_game_db.js $src_sid $dst_sid plat
if (($? != 0)); then
    ./util/error.sh "$title" "merge plat failed"
    exit 1
fi

node ./merge/merge_game_db.js $src_sid $dst_sid world
if (($? != 0)); then
    ./util/error.sh "$title" "merge world failed"
    exit 1
fi
